package com.at.atapp.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
 

import android.os.AsyncTask;
import android.util.Log;
import android.webkit.WebView;
 
public class RestClient extends AsyncTask<Void,Void,Boolean>{
	
	boolean	loginstate = false;
	
	private static HttpClient httpclient = new DefaultHttpClient();
	private HttpPost httppost;
	WebView webview;
	 String data;
	//Response & Entity
	private HttpResponse httpresponse;
	private HttpEntity httpentity;
	
	private ArrayList<NameValuePair>	namevaluepairs = new ArrayList<NameValuePair>();
	
	public RestClient(WebView webview){
		this.webview = webview;
	}
	
	
	protected Boolean doInBackground(Void... params) {
		
		this.loginstate	= false;	
		
		httppost	= new HttpPost("http://www.benbox.org/benbox/wp-login.php");//ip from host (localhost)
		httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));

		
		//add values in pair array
        namevaluepairs.add(new BasicNameValuePair("log", "mic"));
        namevaluepairs.add(new BasicNameValuePair("pwd", "coulalou"));//redirect_to "
        namevaluepairs.add(new BasicNameValuePair("redirect_to", "http://www.benbox.org/benbox/index.php?OperatingSystem=Android"));
        namevaluepairs.add(new BasicNameValuePair("testcookie", "1")); 
        namevaluepairs.add(new BasicNameValuePair("wp-submit", "Anmelden"));
        namevaluepairs.add(new BasicNameValuePair("rememberme", "forever"));
		/*
		httppost	= new HttpPost("https://secure.wer-kennt-wen.de/login/index");//ip from host (localhost)
		
		//add values in pair array
        namevaluepairs.add(new BasicNameValuePair("loginName", "thundermare@t-online.de"));
        namevaluepairs.add(new BasicNameValuePair("pass", "serra"));//redirect_to "
       namevaluepairs.add(new BasicNameValuePair("logIn", "1"));*/
       /*  namevaluepairs.add(new BasicNameValuePair("testcookie", "1")); 
        namevaluepairs.add(new BasicNameValuePair("wp-submit", "Anmelden"));*/
        
		try{
			//Set request data
			httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
			
			//Execute webrequest
			httpresponse	=	httpclient.execute(httppost);
			   data = new BasicResponseHandler().handleResponse(httpresponse);
			 /*
			if(httpresponse.getStatusLine().getStatusCode() == 200){
				
				httpentity	=	httpresponse.getEntity();
				
				if(httpentity != null){
					
					InputStream instream	=	httpentity.getContent();
						this.loginstate	= true;	
						convertStreamToString(instream);
						
						 
					      
				}
			}
			*/
			
		}
		catch(Exception e){

			e.printStackTrace();
		}
		    

		return true;
	}

	protected void onPostExecute(Boolean success) {
        // TODO: do something with the feed
	 	webview.loadData(data, "text/html",null);
		
    }
  
	public boolean webLogin(){
		
		execute();
		
		
		if(this.loginstate){
			
			return true;
		}
		
		return false;
	}
 
    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
 
    /* This is a test function which will connects to a given
     * rest service and prints it's response to Android Log with
     * labels "Praeda".
     */
    public static void connect(String url)
    {
 
        HttpClient httpclient = new DefaultHttpClient();
 
        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 
 
        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            Log.i("Praeda",response.getStatusLine().toString());
 
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release
 
            if (entity != null) {
 
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                Log.i("Praeda",result);
 
                // A Simple JSONObject Creation
                JSONObject json=new JSONObject(result);
                Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
 
                // A Simple JSONObject Parsing
                JSONArray nameArray=json.names();
                JSONArray valArray=json.toJSONArray(nameArray);
                for(int i=0;i<valArray.length();i++)
                {
                    Log.i("Praeda","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
                            +"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
                }
 
                // A Simple JSONObject Value Pushing
                json.put("sample key", "sample value");
                Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
 
                // Closing the input stream will trigger connection release
                instream.close();
            }
 
 
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}